﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Management;

public class VirtualizationManager
{
    public VirtualizationManager()
    {

    }

    public List<ManagementObject> GetVirtualMachines()
    {
        string queryObject = "Msvm_ComputerSystem";

        ConnectionOptions oConn = new ConnectionOptions();
        oConn.Username = ConfigurationSettings.AppSettings["VirtualizationServerUsername"];
        oConn.Password = ConfigurationSettings.AppSettings["VirtualizationServerPassword"];

        List<ManagementObject> computers = new List<ManagementObject>();

        string query = string.Format(@"\\{0}\root\Virtualization", ConfigurationSettings.AppSettings["VirtualizationServer"]);

        ManagementScope oMs = new ManagementScope(query, oConn);
        ObjectQuery oQuery = new ObjectQuery("SELECT * FROM " + queryObject);
        
        ManagementObjectSearcher searcher;

        try
        {
            searcher = new ManagementObjectSearcher(oMs, oQuery);

            foreach (ManagementObject mo in searcher.Get())
            {
                if (mo.Properties["Caption"].Value.ToString() == "Virtual Machine")
                {
                    computers.Add(mo);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        return computers;
    }
}
